package com.own.component.common.util.verification;

import com.own.component.common.em.GenderEnum;
import com.own.constant.ConstantCommon;
import org.apache.commons.lang3.StringUtils;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;

/**
 * IdCardUtil
 *
 * @author chenxueli
 * @date 2021/6/1 11:03
 */
public class IdCardUtil {

    /**
     * 中国公民身份证号码最小长度
     */
    public static final int CHINA_ID_MIN_LENGTH = 15;

    /**
     * 中国公民身份证号码最大长度
     */
    public static final int CHINA_ID_MAX_LENGTH = 18;
    /**
     * 最低年限
     */
    public static final int MIN = 1930;

    /**
     * 省、直辖市代码表
     */
    private static final String[] CITY_CODE = {
            "11", "12", "13", "14", "15", "21", "22", "23", "31", "32", "33", "34", "35", "36", "37", "41",
            "42", "43", "44", "45", "46", "50", "51", "52", "53", "54", "61", "62", "63", "64", "65", "71",
            "81", "82", "91"
    };

    /**
     * 每位加权因子
     */
    private static final int[] POWER = {
            7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2
    };

    /**
     * 第18位校检码
     */
    private static final String[] VERIFY_CODE = {
            "1", "0", "X", "9", "8", "7", "6", "5", "4", "3", "2"
    };
    private static final Map<String, String> CITY_CODE_MAP = new HashMap<>();
    /**
     * 台湾身份首字母对应数字
     */
    private static final Map<String, Integer> TW_FIRST_CODE = new HashMap<>();
    /**
     * 香港身份首字母对应数字
     */
    private static final Map<String, Integer> HK_FIRST_CODE = new HashMap<>();

    static {
        CITY_CODE_MAP.put("11", "北京");
        CITY_CODE_MAP.put("12", "天津");
        CITY_CODE_MAP.put("13", "河北");
        CITY_CODE_MAP.put("14", "山西");
        CITY_CODE_MAP.put("15", "内蒙古");
        CITY_CODE_MAP.put("21", "辽宁");
        CITY_CODE_MAP.put("22", "吉林");
        CITY_CODE_MAP.put("23", "黑龙江");
        CITY_CODE_MAP.put("31", "上海");
        CITY_CODE_MAP.put("32", "江苏");
        CITY_CODE_MAP.put("33", "浙江");
        CITY_CODE_MAP.put("34", "安徽");
        CITY_CODE_MAP.put("35", "福建");
        CITY_CODE_MAP.put("36", "江西");
        CITY_CODE_MAP.put("37", "山东");
        CITY_CODE_MAP.put("41", "河南");
        CITY_CODE_MAP.put("42", "湖北");
        CITY_CODE_MAP.put("43", "湖南");
        CITY_CODE_MAP.put("44", "广东");
        CITY_CODE_MAP.put("45", "广西");
        CITY_CODE_MAP.put("46", "海南");
        CITY_CODE_MAP.put("50", "重庆");
        CITY_CODE_MAP.put("51", "四川");
        CITY_CODE_MAP.put("52", "贵州");
        CITY_CODE_MAP.put("53", "云南");
        CITY_CODE_MAP.put("54", "西藏");
        CITY_CODE_MAP.put("61", "陕西");
        CITY_CODE_MAP.put("62", "甘肃");
        CITY_CODE_MAP.put("63", "青海");
        CITY_CODE_MAP.put("64", "宁夏");
        CITY_CODE_MAP.put("65", "新疆");
        CITY_CODE_MAP.put("71", "台湾");
        CITY_CODE_MAP.put("81", "香港");
        CITY_CODE_MAP.put("82", "澳门");
        CITY_CODE_MAP.put("91", "国外");
        TW_FIRST_CODE.put("A", 10);
        TW_FIRST_CODE.put("B", 11);
        TW_FIRST_CODE.put("C", 12);
        TW_FIRST_CODE.put("D", 13);
        TW_FIRST_CODE.put("E", 14);
        TW_FIRST_CODE.put("F", 15);
        TW_FIRST_CODE.put("G", 16);
        TW_FIRST_CODE.put("H", 17);
        TW_FIRST_CODE.put("J", 18);
        TW_FIRST_CODE.put("K", 19);
        TW_FIRST_CODE.put("L", 20);
        TW_FIRST_CODE.put("M", 21);
        TW_FIRST_CODE.put("N", 22);
        TW_FIRST_CODE.put("P", 23);
        TW_FIRST_CODE.put("Q", 24);
        TW_FIRST_CODE.put("R", 25);
        TW_FIRST_CODE.put("S", 26);
        TW_FIRST_CODE.put("T", 27);
        TW_FIRST_CODE.put("U", 28);
        TW_FIRST_CODE.put("V", 29);
        TW_FIRST_CODE.put("X", 30);
        TW_FIRST_CODE.put("Y", 31);
        TW_FIRST_CODE.put("W", 32);
        TW_FIRST_CODE.put("Z", 33);
        TW_FIRST_CODE.put("I", 34);
        TW_FIRST_CODE.put("O", 35);
        HK_FIRST_CODE.put("A", 1);
        HK_FIRST_CODE.put("B", 2);
        HK_FIRST_CODE.put("C", 3);
        HK_FIRST_CODE.put("R", 18);
        HK_FIRST_CODE.put("U", 21);
        HK_FIRST_CODE.put("Z", 26);
        HK_FIRST_CODE.put("X", 24);
        HK_FIRST_CODE.put("W", 23);
        HK_FIRST_CODE.put("O", 15);
        HK_FIRST_CODE.put("N", 14);
    }

    /**
     * 将15位身份证号码转换为18位
     *
     * @param idCard 15位身份编码
     * @return 18位身份编码
     */
    public static String convert15CardTo18(String idCard) {
        if (idCard.length() != CHINA_ID_MIN_LENGTH) {
            return idCard.length() == CHINA_ID_MAX_LENGTH ? idCard : null;
        }
        if (isNum(idCard)) {
            // 获取出生年月日
            var birthday = idCard.substring(6, 12);
            var birthDate = LocalDate.parse(birthday, DateTimeFormatter.ofPattern("yyMMdd"));
            // 获取出生年(完全表现形式，如：2010)
            var year = String.valueOf(birthDate.getYear());
            var idCard18 = new StringBuilder();
            idCard18.append(idCard, 0, 6)
                    .append(year)
                    .append(idCard.substring(8));
            // 转换字符数组
            var array = idCard18.toString().toCharArray();
            var iCard = convertCharToInt(array);
            var iSum17 = getPowerSum(iCard);
            // 获取校验位
            var sVal = getCheckCode18(iSum17);
            return sVal.length() > 0 ? idCard18.append(sVal).toString() : null;
        }
        return null;
    }

    /**
     * 验证身份证是否合法
     */
    public static boolean validateCard(String idCard) {
        var card = idCard.trim();
        if (validateIdCard18(card) || verificationIdCard15(card)) {
            return true;
        }
        var cardVal = verificationIdCard10(card);
        return cardVal != null && ConstantCommon.TRUE.equals(cardVal[2]);
    }

    /**
     * 验证18位身份编码是否合法
     *
     * @param idCard 身份编码
     * @return 是否合法
     */
    public static boolean validateIdCard18(String idCard) {
        if (idCard.length() == CHINA_ID_MAX_LENGTH) {
            // 前17位
            var code17 = idCard.substring(0, 17);
            // 第18位
            var code18 = idCard.substring(17, CHINA_ID_MAX_LENGTH);
            if (isNum(code17)) {
                var array = code17.toCharArray();
                var iCard = convertCharToInt(array);
                var iSum17 = getPowerSum(iCard);
                // 获取校验位
                var var = getCheckCode18(iSum17);
                return var.length() > 0 && var.equalsIgnoreCase(code18);
            }
        }
        return false;
    }

    /**
     * 验证15位身份编码是否合法
     *
     * @param idCard 身份编码
     * @return 是否合法
     */
    public static boolean verificationIdCard15(String idCard) {
        if (idCard.length() != CHINA_ID_MIN_LENGTH) {
            return false;
        }
        if (isNum(idCard)) {
            var proCode = idCard.substring(0, 2);
            if (CITY_CODE_MAP.get(proCode) == null) {
                return false;
            }
            var birthCode = idCard.substring(6, 12);
            var birthDate = LocalDate.parse(birthCode.substring(0, 2), DateTimeFormatter.ofPattern("yy"));
            return validDate(
                    birthDate.getYear(),
                    Integer.parseInt(birthCode.substring(2, 4)),
                    Integer.parseInt(birthCode.substring(4, 6))
            );
        } else {
            return false;
        }
    }

    /**
     * 验证10位身份编码是否合法
     *
     * @param idCard 身份编码
     * @return 身份证信息数组
     * <p>
     * [0] - 台湾、澳门、香港 [1] - 性别(男M,女F,未知N) [2] - 是否合法(合法true,不合法false)
     * 若不是身份证件号码则返回null
     * </p>
     */
    public static String[] verificationIdCard10(String idCard) {
        var info = new String[3];
        var card = idCard.replaceAll("[\\(|\\)]", "");
        if (card.length() != 8 && card.length() != 9 && idCard.length() != 10) {
            return null;
        }
        // 台湾
        if (idCard.matches("^[a-zA-Z][0-9]{9}$")) {
            info[0] = "台湾";
            var char2 = idCard.substring(1, 2);
            switch (char2) {
                case "1": {
                    info[1] = "M";
                    break;
                }
                case "2": {
                    info[1] = "F";
                    break;
                }
                default: {
                    info[1] = "N";
                    info[2] = "false";
                    return info;
                }
            }
            info[2] = verificationTwCard(idCard) ? "true" : "false";
        }
        // 澳门
        else if (idCard.matches("^[1|5|7][0-9]{6}\\(?[0-9A-Z]\\)?$")) {
            info[0] = "澳门";
            info[1] = "N";
        }
        // 香港
        else if (idCard.matches("^[A-Z]{1,2}[0-9]{6}\\(?[0-9A]\\)?$")) {
            info[0] = "香港";
            info[1] = "N";
            info[2] = validateHKCard(idCard) ? "true" : "false";
        } else {
            return null;
        }
        return info;
    }

    /**
     * 验证台湾身份证号码
     *
     * @param idCard 身份证号码
     * @return 验证码是否符合
     */
    public static boolean verificationTwCard(String idCard) {
        var start = idCard.substring(0, 1);
        var mid = idCard.substring(1, 9);
        var end = idCard.substring(9, 10);
        var iStart = TW_FIRST_CODE.get(start);
        int sum = iStart / 10 + (iStart % 10) * 9;
        var chars = mid.toCharArray();
        int index = 8;
        for (char c : chars) {
            sum = sum + Integer.parseInt(c + "") * index;
            index--;
        }
        return (sum % 10 == 0 ? 0 : (10 - sum % 10)) == Integer.parseInt(end);
    }

    /**
     * 验证香港身份证号码(存在Bug，部份特殊身份证无法检查)
     * <p>
     * 身份证前2位为英文字符，如果只出现一个英文字符则表示第一位是空格，对应数字58 前2位英文字符A-Z分别对应数字10-35
     * 最后一位校验码为0-9的数字加上字符"A"，"A"代表10
     * </p>
     * <p>
     * 将身份证号码全部转换为数字，分别对应乘9-1相加的总和，整除11则证件号码有效
     * </p>
     *
     * @param idCard 身份证号码
     * @return 验证码是否符合
     */
    @SuppressWarnings("all")
    public static boolean validateHKCard(String idCard) {
        String card = idCard.replaceAll("[\\(|\\)]", "");
        int sum;
        if (card.length() == 9) {
            sum = (Integer.valueOf(card.substring(0, 1).toUpperCase().toCharArray()[0]) - 55) * 9 + (Integer.valueOf(card.substring(1, 2).toUpperCase().toCharArray()[0]) - 55) * 8;
            card = card.substring(1, 9);
        } else {
            sum = 522 + (Integer.valueOf(card.substring(0, 1).toUpperCase().toCharArray()[0]) - 55) * 8;
        }
        var mid = card.substring(1, 7);
        var end = card.substring(7, 8);
        var chars = mid.toCharArray();
        int iflag = 7;
        for (var c : chars) {
            sum = sum + Integer.parseInt(c + "") * iflag;
            iflag--;
        }
        if ("A".equalsIgnoreCase(end)) {
            sum = sum + 10;
        } else {
            sum = sum + Integer.parseInt(end);
        }
        return sum % 11 == 0;
    }

    /**
     * 将字符数组转换成数字数组
     *
     * @param ca 字符数组
     * @return 数字数组
     */
    public static int[] convertCharToInt(char[] ca) {
        int len = ca.length;
        int[] iArr = new int[len];
        try {
            for (int i = 0; i < len; i++) {
                iArr[i] = Integer.parseInt(String.valueOf(ca[i]));
            }
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }
        return iArr;
    }

    /**
     * 将身份证的每位和对应位的加权因子相乘之后，再得到和值
     *
     * @param iArr 数组
     * @return 身份证编码。
     */
    public static int getPowerSum(int[] iArr) {
        int iSum = 0;
        if (POWER.length == iArr.length) {
            for (int i = 0; i < iArr.length; i++) {
                for (int j = 0; j < POWER.length; j++) {
                    if (i == j) {
                        iSum = iSum + iArr[i] * POWER[j];
                    }
                }
            }
        }
        return iSum;
    }

    /**
     * 将power和值与11取模获得余数进行校验码判断
     *
     * @param iSum 数字
     * @return 校验位
     */
    public static String getCheckCode18(int iSum) {
        return VERIFY_CODE[iSum % 11];
    }

    /**
     * 根据身份编号获取年龄
     *
     * @param idCard 身份编号
     * @return 年龄
     */
    public static int getAgeByIdCard(String idCard) {
        if (idCard.length() == CHINA_ID_MIN_LENGTH) {
            idCard = convert15CardTo18(idCard);
        }
        if (StringUtils.isEmpty(idCard)) {
            return 0;
        }
        var year = idCard.substring(6, 10);
        return LocalDate.now().getYear() - Integer.parseInt(year);
    }

    /**
     * 根据身份编号获取生日
     *
     * @param idCard 身份编号
     * @return 生日(yyyyMMdd)
     */
    public static String getBirthByIdCard(String idCard) {
        if (StringUtils.isEmpty(idCard)) {
            return "";
        }
        var length = idCard.length();
        if (length < CHINA_ID_MIN_LENGTH) {
            return null;
        }
        if (length == CHINA_ID_MIN_LENGTH) {
            return StringUtils.isEmpty(idCard) ? "" : idCard.substring(6, 14);
        }
        return idCard.substring(6, 14);
    }

    /**
     * 根据身份编号获取生日年
     *
     * @param idCard 身份编号
     * @return 生日(yyyy)
     */
    public static Short getYearByIdCard(String idCard) {
        if (StringUtils.isEmpty(idCard)) {
            return 0;
        }
        var length = idCard.length();
        if (length < CHINA_ID_MIN_LENGTH) {
            return null;
        }
        if (length == CHINA_ID_MIN_LENGTH) {
            return StringUtils.isEmpty(idCard) ? 0 : Short.valueOf(idCard.substring(6, 10));
        }
        return Short.valueOf(idCard.substring(6, 10));
    }

    /**
     * 根据身份编号获取生日月
     *
     * @param idCard 身份编号
     * @return 生日(MM)
     */
    public static Short getMonthByIdCard(String idCard) {
        if (StringUtils.isEmpty(idCard)) {
            return 0;
        }
        var length = idCard.length();
        if (length < CHINA_ID_MIN_LENGTH) {
            return null;
        }
        if (length == CHINA_ID_MIN_LENGTH) {
            return StringUtils.isEmpty(idCard) ? 0 : Short.valueOf(idCard.substring(10, 12));
        }
        return Short.valueOf(idCard.substring(10, 12));
    }

    /**
     * 根据身份编号获取生日天
     *
     * @param idCard 身份编号
     * @return 生日(dd)
     */
    public static Short getDateByIdCard(String idCard) {
        if (StringUtils.isEmpty(idCard)) {
            return 0;
        }
        var length = idCard.length();
        if (length < CHINA_ID_MIN_LENGTH) {
            return null;
        }
        if (length == CHINA_ID_MIN_LENGTH) {
            idCard = convert15CardTo18(idCard);
            return StringUtils.isEmpty(idCard) ? 0 : Short.valueOf(idCard.substring(6, 10));
        }
        return Short.valueOf(idCard.substring(6, 10));
    }

    /**
     * 根据身份编号获取性别
     *
     * @param idCard 身份编号
     * @return 性别(M = 男, F = 女, N = 未知)
     */
    public static GenderEnum getGenderByIdCard(String idCard) {
        if (idCard.length() == CHINA_ID_MIN_LENGTH) {
            idCard = convert15CardTo18(idCard);
        }
        if (StringUtils.isEmpty(idCard)) {
            return GenderEnum.NULL;
        }
        return Integer.parseInt(idCard.substring(16, 17)) % 2 != 0 ? GenderEnum.MALE : GenderEnum.FEMALE;
    }

    /**
     * 根据身份编号获取户籍省份
     *
     * @param idCard 身份编码
     * @return 省级编码。
     */
    public static String getProvinceByIdCard(String idCard) {
        var len = idCard.length();
        if (len == CHINA_ID_MIN_LENGTH || len == CHINA_ID_MAX_LENGTH) {
            return CITY_CODE_MAP.get(idCard.substring(0, 2));
        }
        return CITY_CODE_MAP.get("");
    }

    /**
     * 数字验证
     *
     * @param var 内容
     * @return 提取的数字
     */
    public static boolean isNum(String var) {
        return var != null && !"".equals(var) && var.matches("^[0-9]*$");
    }

    /**
     * 验证小于当前日期 是否有效
     *
     * @param iYear  待验证日期(年)
     * @param iMonth 待验证日期(月 1-12)
     * @param iDate  待验证日期(日)
     * @return 是否有效
     */
    public static boolean validDate(int iYear, int iMonth, int iDate) {
        var year = LocalDate.now().getYear();
        if (iYear < MIN || iYear >= year) {
            return false;
        }
        if (iMonth < 1 || iMonth > 12) {
            return false;
        }
        int datePerMonth = switch (iMonth) {
            case 4, 6, 9, 11 -> 30;
            case 2 -> ((iYear % 4 == 0 && iYear % 100 != 0 || iYear % 400 == 0) && iYear > MIN) ? 29 : 28;
            default -> 31;
        };
        return (iDate >= 1) && (iDate <= datePerMonth);
    }

}
